const baseURL = 'https://tea.qingnian8.com'

const httpInterceptor = {
	invoke(options) {
		let token = uni.getStorageSync('token')
		options.header = {
			['access-key']: '140760',
			Authorization: token,
			...options.header
		}
		options.header['acess-key'] = '140760'
		options.timeout = 10 * 1000
		options.url = baseURL + options.url
		console.log(options)
	}
}

// 请求拦截器
uni.addInterceptor('request', httpInterceptor)

const request = (options) => {
	// uni.showLoading({
	// 	mask: true,
	// 	title: "数据加载中...",
	// });
		
	uni.showNavigationBarLoading()
	
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			success(res) {
				// 获取当前页面的栈
				const pages = getCurrentPages();
				console.log(pages, '==============')
				// 获取当前页面
				const currentPage = pages[pages.length - 1];
				// 获取当前页面的路由
				const currentRoute = currentPage.route;
				// 定义401不需要登录的路由数组
				const routes = ["pages/index/index"]
				if (res.statusCode === 200) {
					if (res.data.errCode == 0) {
						resolve(res.data);
					} else if (res.data.errCode === 401 && !routes.includes(currentRoute)) {
						uni.showModal({
							title: "温馨提示",
							content: "您还没有登录，是否去登录",
							success(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: "/pages/login/login",
									});
								} else {
									uni.navigateBack({
										delta: 1,
									});
								}
							},
						});
					} else if (res.data.errCode === 400) {
						uni.showToast({
							title: res.data.errMsg,
							icon: 'none'
						})
					} else {
						resolve(res.data);
					}
				} else {
					reject(res.data);
				}
			},
			// 响应失败
			fail(err) {
				console.log(err)
				uni.showToast({
					icon: "none",
					title: "网络错误, 换个网络试试",
				});
				reject(err.errMsg);
			},
			complete() {
				uni.hideNavigationBarLoading()
			},
		});
	});
};

export default request